<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" th:href="@{/css/plugins/layui/css/layui.css}">
    <style>
        body {
            padding: 10px;
        }
    </style>
</head>
<body>
<div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-inline layui-input-wrap">
                <input type="text" id="roleName" name="roleName" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <input type="hidden" id="pIds" value="">
        <div class="layui-inline">
            <label class="layui-form-label">权限列表</label>
            <div class="layui-input-inline layui-input-wrap">
                <div id="role-tree"></div>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/plugins/layui/layui.js}"></script>
<script>
    layui.use(function (){
        var tree = layui.tree;
        var $ = layui.$;
        var util = layui.util;
        let data = []
        $.ajax({
            url: '/permission/treelist',
            type: 'get',
            dataType: 'json',
            async: false,
            success: function (d) {
                data = d.data
            }
        })
        tree.render({
            elem: '#role-tree',
            data: data,
            customName: { // 自定义 data 字段名 --- 2.8.14+
                id: 'id',
                title: 'menuName',
                children: 'children'
            },
            showCheckbox: true,  // 是否显示复选框
            onlyIconControl: true,  // 是否仅允许节点左侧图标控制展开收缩
            id: 'demo',
            isJump: true, // 是否允许点击节点时弹出新窗口跳转
            click: function(obj){
                var data = obj.data;  //获取当前点击的节点数据
                layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
            },
            oncheck: function(obj){
                $('#pIds').val("")
                let checkedData = tree.getChecked('demo');
                // 遍历checkedData 获取所有节点的id
                let ids = []
                getAllCheckedIds(ids,checkedData);
                $('#pIds').val(ids.join(","))
            }
        });

        function getAllCheckedIds(ids,checkedData){
            if(checkedData.length > 0){
                for(let i = 0; i < checkedData.length; i++){
                    ids.push(checkedData[i].id);
                    if(checkedData[i].children && checkedData[i].children.length > 0){
                        getAllCheckedIds(ids,checkedData[i].children);
                    }
                }
            }
        }
    })
</script>
</body>
</html>
